package com.origin.niuke.simulation;

/**
 * @author yzh
 * @date 2022/7/9 21:27
 * 把字符串转换成整数(atoi)
 * 算法：模拟
 */
public class NC100 {

    public int StrToInt(String s) {
        int len = s.length();
        if (len == 0) return 0;
        int idx = 0;
        while (idx < len && s.charAt(idx) == ' ') ++idx;
        if (idx == len) return 0;
        char c = s.charAt(idx);
        int flag = 1;
        if (c == '+') ++idx;
        else if (c == '-') {
            ++idx;
            flag = -1;
        }
        int ans = 0;
        for (; idx < len; idx++) {
            c = s.charAt(idx);
            if (c < '0' || c > '9') break;
            int num = (c - '0') * flag;
            if (ans > Integer.MAX_VALUE / 10 || ans == Integer.MAX_VALUE / 10 && num > Integer.MAX_VALUE % 10)
                return Integer.MAX_VALUE;
            if (ans < Integer.MIN_VALUE / 10 || ans == Integer.MIN_VALUE / 10 && num < Integer.MIN_VALUE % 10)
                return Integer.MIN_VALUE;
            ans = ans * 10 + num;
        }
        return ans;
    }

}
